package com.dhsc.util;

import com.dhsc.domain.yypt.HttpRequestObj;
import com.dhsc.domain.yypt.ResponseObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName:  HttpClientUtil
 * @Description: httpclient工具类
 * @date:   2024年6月11日 上午11:06:55       
 * @author: clong
 * @Copyright:  东海运营
 */
@Slf4j
public class HttpClientUtil
{
	private static final String utf8 = "UTF-8";
	
	private HttpClientUtil()
	{

	}

	private static void requestParams(Object model, List<NameValuePair> list) throws IllegalArgumentException, IllegalAccessException
	{
		if (null == model)
		{
			return;
		}
		for (Field field : model.getClass().getDeclaredFields())
		{
			field.setAccessible(true);
			if (null == field.get(model))
			{
				continue;
			}
			BasicNameValuePair pair = new BasicNameValuePair(field.getName(), field.get(model).toString());
			list.add(pair);
		}
	}

	public static String getRequest(String url, Object bean) throws URISyntaxException, IllegalArgumentException, IllegalAccessException, IOException
	{
		URIBuilder uriBuilder = new URIBuilder(url);
		List<NameValuePair> list = new ArrayList<>();
		requestParams(bean, list);

		uriBuilder.setParameters(list);

		HttpGet httpGet = new HttpGet(uriBuilder.build());
		RequestConfig config = SpringContextUtil.getBean(RequestConfig.class);
		CloseableHttpClient httpClient = SpringContextUtil.getBean(CloseableHttpClient.class);
		// 装载配置信息
		httpGet.setConfig(config);
		// 发起请求
		CloseableHttpResponse response = httpClient.execute(httpGet);
		// 判断状态码是否为200
		if (response.getStatusLine().getStatusCode() == 200)
		{
			// 返回响应体的内容
			return EntityUtils.toString(response.getEntity(), utf8);
		}
		return "";
	}

	public static String postRequest(String url, Object bean)
	{
		String res = "";
		try (CloseableHttpClient httpClient = HttpClients.createDefault();){
			
			CloseableHttpResponse response = null;
			// 创建POST请求对象
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> list = new ArrayList<>();

			requestParams(bean, list);
			// 使用URL实体转换工具
			UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, utf8);
			httpPost.setEntity(entityParam);

			// 浏览器表示
			httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
			// 传输的类型
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
			// 执行请求
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			res= EntityUtils.toString(entity, utf8);
		} catch (Exception e) {
			log.error("发送POST请求出错。" + url,e);
		}
		return res;
	}
	
	/**
	 * @Title: get   
	 * @Description: get请求
	 * @param req
	 * @return ResponseObject
	 * @author: clong
	 * @date:   2024年3月25日 上午11:58:09
	 */
	public static ResponseObject get(HttpRequestObj req)
	{
		ResponseObject resp = new ResponseObject();
		HttpGet httpGet = new HttpGet(req.getUrl());
		
		try (CloseableHttpClient httpClient = HttpClients.createDefault();)
		{
			Map<String, Object> reqHeads = req.getReqHeads();

			if (!reqHeads.isEmpty())
			{
				httpGet.setHeaders(createHeaders(reqHeads));
			}
			
			CloseableHttpResponse response = httpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			
			resp.setStatus(statusCode);
			HttpEntity entity = response.getEntity();
			resp.setData(EntityUtils.toString(entity, utf8));
		}
		catch (Exception e)
		{
			log.error("发送get请求异常", e);
			resp.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
			resp.setMessage(e.getMessage());
		}
		return resp;
	}
	
	/**
	 * @Title: createHeaders   
	 * @Description: 创建请求头
	 * @param header
	 * @return Header[]
	 * @author: clong
	 * @date:   2024年3月25日 上午11:58:02
	 */
	private static Header[] createHeaders(Map<String, Object> header)
	{
		if (header.isEmpty())
		{
			return new Header[0];
		}
		List<Header> headers = new ArrayList<>();
		for (String key : header.keySet())
		{
			headers.add(new BasicHeader(key, (String) header.get(key)));
		}
		return headers.toArray(new Header[]{});
	}
	
	public static String postRequestCas(String url, String body, String token)
	{
		String result = "";
		try (CloseableHttpClient httpClient = HttpClients.createDefault();)
		{
			CloseableHttpResponse response = null;
			// 创建POST请求对象
			HttpPost httpPost = new HttpPost(url);
			
			// 使用URL实体转换工具
			StringEntity s = new StringEntity(body, utf8);
			s.setContentEncoding(utf8);
			s.setContentType("application/json");//发送json数据需要设置contentType
			
			httpPost.setEntity(s);
	
			// 传输的类型
			httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
			
			httpPost.addHeader("Authorization", "Bearer " + token);
			
			// 执行请求
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			result = EntityUtils.toString(entity, utf8); 
		}catch (Exception e) {
			log.error("发送POSTCAS请求出错。" + url,e);
		}
		return result;
	}

	public static String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			//获取URLConnection对象对应的输出流
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));

			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream(),"UTF-8"));

			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！"+e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return result;
	}
}
